package com.zego.zegowawaji_server.utils;

import android.text.TextUtils;

import com.zego.base.bean.CustomZegoUser;
import com.zego.base.utils.AppLogger;
import com.zego.zegowawaji_server.listener.IRoomClient;
import com.zego.zegowawaji_server.manager.CommandSeqManager;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 合成CMD发送指令
 * Created by Su on 2017/12/7.
 */
public class SynthCmd {

    private static IRoomClient mRoomClient;     // 房间信息

    public static void setRoomClient(IRoomClient roomClient) {
        mRoomClient = roomClient;
    }

    private static List<CustomZegoUser> getQueueUsers() {
        if (mRoomClient == null) {
            return Collections.synchronizedList(new ArrayList<CustomZegoUser>());
        }
        return mRoomClient.getQueueUser();
    }

    /**
     * 通知某人准备上机
     */
    public static String gameReadyCmd(String userId, String userName, int seq) {
        JSONObject json = new JSONObject();
        try {
            json.put(JsonKey.KEY_SEQ, seq);
            json.put(JsonKey.KEY_CMD, Command.CMD_GAME_READY);

            JSONObject playerJson = new JSONObject();
            playerJson.put(JsonKey.KEY_USER_ID, userId);
            playerJson.put(JsonKey.KEY_USER_NAME, userName);

            JSONObject dataJson = new JSONObject();
            dataJson.put(JsonKey.KEY_PLAYER, playerJson);
            dataJson.put(JsonKey.KEY_TIME_STAMP, System.currentTimeMillis());

            JSONArray queueData = new JSONArray();
            for (CustomZegoUser zegoUser : getQueueUsers()) {
                JSONObject jsonUser = new JSONObject();
                jsonUser.put(JsonKey.KEY_USER_ID, zegoUser.userID);
                jsonUser.put(JsonKey.KEY_USER_NAME, zegoUser.userName);
                jsonUser.put(JsonKey.KEY_USER_AVATAR, zegoUser.avatar);

                queueData.put(jsonUser);
            }
            dataJson.put(JsonKey.KEY_USER_QUEUE, queueData);

            json.put(JsonKey.KEY_DATA, dataJson);
        } catch (JSONException e) {
            AppLogger.getInstance().writeLog("generateReadyCommand failed. " + e);
        }
        return json.toString();
    }

    /**
     * 回复收到确认上机或者放弃玩游戏指令
     */
    public static String startOrAbandonReplyCmd(JSONObject requestData) {
        JSONObject json = new JSONObject();
        try {
            int seq = CommandSeqManager.getInstance().getAndIncreaseSequence();
            json.put(JsonKey.KEY_SEQ, seq);
            json.put(JsonKey.KEY_CMD, Command.CMD_START_OR_ABANDON_GAME_REPLY);

            JSONObject jsonData = new JSONObject();
            jsonData.put(JsonKey.KEY_SEQ, requestData.optInt(JsonKey.KEY_SEQ));
            JSONObject sessionData = requestData.optJSONObject(JsonKey.KEY_SESSION_DATA);
            if (sessionData != null) {
                jsonData.put(JsonKey.KEY_SESSION_DATA, sessionData);
            }
            jsonData.put(JsonKey.KEY_TIME_STAMP, System.currentTimeMillis());

            JSONArray queueData = new JSONArray();
            for (CustomZegoUser zegoUser : getQueueUsers()) {
                JSONObject jsonUser = new JSONObject();
                jsonUser.put(JsonKey.KEY_USER_ID, zegoUser.userID);
                jsonUser.put(JsonKey.KEY_USER_NAME, zegoUser.userName);
                jsonUser.put(JsonKey.KEY_USER_AVATAR, zegoUser.avatar);

                queueData.put(jsonUser);
            }
            jsonData.put(JsonKey.KEY_USER_QUEUE, queueData);

            json.put(JsonKey.KEY_DATA, jsonData);
        } catch (JSONException e) {
            AppLogger.getInstance().writeLog("generateStartOrAbandonReplyCommand failed. " + e);
        }
        return json.toString();
    }

    /**
     * 回复收到预约申请，并告知预约结果
     */
    public static String applyReplyCmd(String userId, String userName, int queueSize, JSONObject requestData) {
        JSONObject json = new JSONObject();
        try {
            json.put(JsonKey.KEY_SEQ, CommandSeqManager.getInstance().getAndIncreaseSequence());
            json.put(JsonKey.KEY_CMD, Command.CMD_APPOINTMENT_REPLY);

            JSONObject playerJson = new JSONObject();
            playerJson.put(JsonKey.KEY_USER_ID, userId);
            playerJson.put(JsonKey.KEY_USER_NAME, userName);

            JSONObject dataJson = new JSONObject();
            dataJson.put(JsonKey.KEY_RESULT, 0);
            dataJson.put(JsonKey.KEY_PLAYER, playerJson);
            dataJson.put(JsonKey.KEY_ORDER_INDEX, queueSize);

            dataJson.put(JsonKey.KEY_SEQ, requestData.optInt(JsonKey.KEY_SEQ));
            JSONObject sessionData = requestData.optJSONObject(JsonKey.KEY_SESSION_DATA);
            if (sessionData != null) {
                dataJson.put(JsonKey.KEY_SESSION_DATA, sessionData);
            }

            dataJson.put(JsonKey.KEY_TIME_STAMP, System.currentTimeMillis());

            // 携带自己的信息
            dataJson.put(JsonKey.KEY_USER_AVATAR, requestData.optJSONObject(JsonKey.KEY_DATA).optString(JsonKey.KEY_USER_AVATAR));
            dataJson.put(JsonKey.KEY_USER_NICKNAME, requestData.optJSONObject(JsonKey.KEY_DATA).optString(JsonKey.KEY_USER_NICKNAME));

            JSONArray queueData = new JSONArray();
            for (CustomZegoUser zegoUser : getQueueUsers()) {
                JSONObject jsonUser = new JSONObject();
                jsonUser.put(JsonKey.KEY_USER_ID, zegoUser.userID);
                jsonUser.put(JsonKey.KEY_USER_NAME, zegoUser.userName);
                jsonUser.put(JsonKey.KEY_USER_AVATAR, zegoUser.avatar);

                queueData.put(jsonUser);
            }
            dataJson.put(JsonKey.KEY_USER_QUEUE, queueData);

            json.put(JsonKey.KEY_DATA, dataJson);
        } catch (JSONException e) {
            AppLogger.getInstance().writeLog("generateAppointmentReplyCommand failed, userId: %s; userName: %s", userId, userName);
        }
        return json.toString();
    }


    /**
     * 回复收到取消预约申请，并告知取消预约结果
     * @param result  1: 成功 0 ： 不成功
     */
    public static String applyCancelCmd(String userId, String userName, int result, JSONObject requestData) {
        JSONObject json = new JSONObject();
        try {
            json.put(JsonKey.KEY_SEQ, CommandSeqManager.getInstance().getAndIncreaseSequence());
            json.put(JsonKey.KEY_CMD, Command.CMD_CANCEL_APPOINTMENT_REPLY);

            JSONObject playerJson = new JSONObject();
            playerJson.put(JsonKey.KEY_USER_ID, userId);
            playerJson.put(JsonKey.KEY_USER_NAME, userName);

            JSONObject dataJson = new JSONObject();
            dataJson.put(JsonKey.KEY_RESULT, result);
            dataJson.put(JsonKey.KEY_PLAYER, playerJson);

            dataJson.put(JsonKey.KEY_SEQ, requestData.optInt(JsonKey.KEY_SEQ));
            JSONObject sessionData = requestData.optJSONObject(JsonKey.KEY_SESSION_DATA);
            if (sessionData != null) {
                dataJson.put(JsonKey.KEY_SESSION_DATA, sessionData);
            }

            dataJson.put(JsonKey.KEY_TIME_STAMP, System.currentTimeMillis());

            JSONArray queueData = new JSONArray();
            for (CustomZegoUser zegoUser : getQueueUsers()) {
                JSONObject jsonUser = new JSONObject();
                jsonUser.put(JsonKey.KEY_USER_ID, zegoUser.userID);
                jsonUser.put(JsonKey.KEY_USER_NAME, zegoUser.userName);
                jsonUser.put(JsonKey.KEY_USER_AVATAR, zegoUser.avatar);

                queueData.put(jsonUser);
            }
            dataJson.put(JsonKey.KEY_USER_QUEUE, queueData);

            json.put(JsonKey.KEY_DATA, dataJson);
        } catch (JSONException e) {
            AppLogger.getInstance().writeLog("generateAppointmentReplyCommand failed, userId: %s; userName: %s", userId, userName);
        }
        return json.toString();
    }

    /**
     * 生成游戏结束CMD指令: 存预约中读取用户
     */
    public static String gameOverCmd(List<CustomZegoUser> queueMembers, int result, String userId, String userName, int seq) {
        CustomZegoUser customZegoUser = null;
        for (CustomZegoUser zegoUser : queueMembers) {
            if (TextUtils.equals(userId, zegoUser.userID)) {
                customZegoUser = zegoUser;
                break;
            }
        }

        JSONObject json = new JSONObject();
        try {
            json.put(JsonKey.KEY_SEQ, seq);
            json.put(JsonKey.KEY_CMD, Command.CMD_GAME_RESULT);

            JSONObject playerJson = new JSONObject();
            playerJson.put(JsonKey.KEY_USER_ID, userId);
            playerJson.put(JsonKey.KEY_USER_NAME, userName);
            if (customZegoUser != null) {
                playerJson.put(JsonKey.KEY_USER_AVATAR, customZegoUser.avatar);
                playerJson.put(JsonKey.KEY_USER_NICKNAME, customZegoUser.nickName);
            }

            JSONObject dataJson = new JSONObject();
            dataJson.put(JsonKey.KEY_RESULT, result);
            dataJson.put(JsonKey.KEY_PLAYER, playerJson);
            dataJson.put(JsonKey.KEY_TIME_STAMP, System.currentTimeMillis());

            JSONArray queueData = new JSONArray();
            for (CustomZegoUser zegoUser : getQueueUsers()) {
                JSONObject jsonUser = new JSONObject();
                jsonUser.put(JsonKey.KEY_USER_ID, zegoUser.userID);
                jsonUser.put(JsonKey.KEY_USER_NAME, zegoUser.userName);
                jsonUser.put(JsonKey.KEY_USER_AVATAR, zegoUser.avatar);

                queueData.put(jsonUser);
            }
            dataJson.put(JsonKey.KEY_USER_QUEUE, queueData);

            json.put(JsonKey.KEY_DATA, dataJson);
        } catch (JSONException e) {
            AppLogger.getInstance().writeLog("generateGameOverCommand failed. " + e);
        }
        return json.toString();
    }
}
